package com.ping.study.service.tx;

import com.ping.study.model.vo.tx.MatchInfo;
import com.ping.study.model.vo.tx.MatchResponse;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class MatchService {

    private final WebClient webClient;
    private static final DateTimeFormatter DATE_FORMATTER =
            DateTimeFormatter.ofPattern("yyyy-MM-dd");

    public MatchService(WebClient.Builder webClientBuilder) {
        this.webClient = webClientBuilder
                .baseUrl("https://matchweb.sports.qq.com")
                .build();
    }

    /**
     * 获取指定日期范围内所有NBA季后赛(matchType=2)的直播ID
     */
    public List<String> getPlayoffLiveIdsBlocking(LocalDate startDate, LocalDate endDate) {
        return webClient.get()
                .uri(uriBuilder -> uriBuilder
                        .path("/matchUnion/list")
                        .queryParam("columnId", 100000)
                        .queryParam("startTime", startDate.format(DATE_FORMATTER))
                        .queryParam("endTime", endDate.format(DATE_FORMATTER))
                        .build())
                .retrieve()
                .bodyToMono(MatchResponse.class)
                .flatMapMany(response -> {
                    if (response.getCode() != 0 || response.getData() == null) {
                        return Flux.error(new RuntimeException("API返回异常: " + response.getMsg()));
                    }
                    // 提取所有matchType=2的比赛
                    List<String> liveIds = response.getData().values().stream()
                            .flatMap(List::stream)
                            .filter(match -> "2".equals(match.getMatchType()))
                            .map(MatchInfo::getLiveId)
                            .collect(Collectors.toList());
                    return Flux.fromIterable(liveIds);
                })
                .collectList()
                .block(); // 阻塞等待结果
    }

    /**
     * 获取完整比赛信息（过滤matchType=2）
     */
}